import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "../stores/user";

const authItemName = "authorize";

const accessHeader = () => {
    return {
        Authorization: `Bearer ${takeAccessToken()}`,
    };
};

const defaultError = (error) => {
    console.error(error);
    ElMessage.error("发生了一些错误，请联系管理员");
};

const defaultFailure = (message, status, url) => {
    console.warn(`请求地址: ${url}, 状态码: ${status}, 错误信息: ${message}`);
    ElMessage.warning(message);
};

export function takeAccessToken() {
    const str = localStorage.getItem(authItemName) || sessionStorage.getItem(authItemName);
    if (!str) return null;
    const authObj = JSON.parse(str);
    if (new Date(authObj.expire) <= new Date()) {
        deleteAccessToken();
        ElMessage.warning("登录状态已过期，请重新登录！");
        return null;
    }
    return authObj.token;
}

function storeAccessToken(remember, token, expire) {
    const authObj = {
        token: token,
        expire: expire,
    };
    const str = JSON.stringify(authObj);
    if (remember) localStorage.setItem(authItemName, str);
    else sessionStorage.setItem(authItemName, str);
}

function deleteAccessToken() {
    localStorage.removeItem(authItemName);
    sessionStorage.removeItem(authItemName);
}

function internalPost(url, data, headers, success, failure, error = defaultError) {
    axios
        .post(url, data, { headers: headers })
        .then(({ data }) => {
            if (data.code === 200) success(data.data);
            else failure(data.message, data.code, url);
        })
        .catch((err) => error(err));
}

function internalGet(url, headers, success, failure, error = defaultError) {
    axios
        .get(url, { headers: headers })
        .then(({ data }) => {
            if (data.code === 200) success(data.data);
            else failure(data.message, data.code, url);
        })
        .catch((err) => error(err));
}

function login(username, password, remember, success, failure = defaultFailure) {
    internalPost(
        "/api/auth/login",
        {
            username: username,
            password: password,
        },
        {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        (data) => {
            storeAccessToken(remember, data.token, data.expire);
            ElMessage.success(`登录成功，欢迎 ${data.username} 来到我们的系统`);
            success(data);
        },
        failure
    );
}

function post(url, data, success, failure = defaultFailure) {
    internalPost(url, data, accessHeader(), success, failure);
}

function logout(success, failure = defaultFailure) {
    get(
        "/api/auth/logout",
        () => {
            deleteAccessToken();
            ElMessage.success(`退出登录成功，欢迎您再次使用`);
            success();
        },
        failure
    );
}
function get(url, success, failure = defaultFailure) {
    url, accessHeader(), success, failure;
}

// function return_get(url, success, failure = defaultFailure, error = defaultError) {
//     return new Promise((resolve, reject) => {
//         axios

//             .get(url, { headers: accessHeader() })

//             .then(({ data }) => {
//                 if (data.code === 200) {
//                     success(data.data);

//                     resolve(data.data); // 解析Promise，并返回数据
//                 } else {
//                     failure(data.message, data.code, url);

//                     reject(new Error(data.message)); // 拒绝Promise，并传递错误
//                 }
//             })

//             .catch((err) => {
//                 error(err);

//                 reject(err); // 拒绝Promise，并传递错误
//             });
//     });
// }

function unauthorized() {
    return !takeAccessToken();
}

axios.defaults.headers.common["Authorization"] = `Bearer ${takeAccessToken()}`;

//主题相关接口
export const createSubject = async (title) => {
    return axios.post("", { title });
};

export const getSubject = async () => {
    let data = await axios.get("/api/chatAI/findAllTopic");
    // console.log(data.data.data);
    return data.data.data;
};

export const deleteSubject = (topic) => axios.delete("/api/chatAI/deleteTopic", { params: { topic } });

export const changeSubjectTitle = async (id, oldtitle, newtitle) => {
    await axios.post("/api/chatAI/updateTopic", {
        id: id,
        oldTopic: oldtitle,
        newTopic: newTitle,
    });
};

//问题相关
export const getQuestions = (uname, topicname) => {
    return axios.get("/api/chatAI/getChatContents", {
        headers: {
            "Content-Type": "application/json; charset=UTF-8",
        },
        params: {
            username: uname,
            topic: encodeURI(topicname), // 使用 encodeURI 编码中文字符
        },
    });
};

//用户信息相关
export const getUserInf = async () => {
    get("/api/accounts/findAllDetails", (data) => {
        console.log(data);
        saveUserToPinia(data);
    });
};

export const saveUserToPinia = (user) => {
    const store = useUserStore();
    // user.token = user.token.token;
    store.login(user);
};

export { post, get, login, logout, unauthorized };
